/*
 * @version: 1.2.3
 * @Date: 2022-11-29 15:57:49
 * @LastEditors: 林祥柯
 * @LastEditTime: 2022-12-15 17:57:06
 * @Description: 
 */
//通过 Overlay 实现 Toast
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:happy_elf_app/utils/adaption.dart';
import 'package:happy_elf_app/utils/globalKey.dart';

enum GravityPosition { top, center, bottom }

List<OverlayEntry> _entryList = [];
bool _overlayStatus = true;
OverlayState overlayState = Global.navigatorKey.currentState!.overlay!;

class Toast {
  static Timer? countTimer;
  static bool isShow = false;
  static void show(
      {required BuildContext context,
      required String message,
      bool immediate = true,
      TextStyle textStyle = const TextStyle(color: Colors.white),
      final bgColor = const Color(0x99000000),
      GravityPosition gravity = GravityPosition.center,
      count = -1,
      countCallback,
      delay = const Duration(milliseconds: 1500)}) {
    double deviceHeight = MediaQuery.of(context).size.height;
    double deviceWidth = MediaQuery.of(context).size.width;
    _overlayStatus = true;

    // 创建 overlayEntry
    OverlayEntry overlayEntry = OverlayEntry(builder: (overlayContext) {
      var renderObject = context.findRenderObject();
      //获取元素大小
      Size renderSize = renderObject!.paintBounds.size;
      //获取元素位置
      var renderPosition = renderObject.getTransformTo(null).getTranslation();
      //GravityPosition.right时，弹窗在相机预览中间
      var left = renderPosition[0] + renderSize.width / 2 - deviceWidth / 2;
      return Positioned(
          bottom: gravity == GravityPosition.bottom
              ? deviceHeight * 0.1
              : gravity == GravityPosition.center
                  ? deviceHeight * 0.45
                  : null,
          top: gravity == GravityPosition.top ? deviceHeight * 0.1 : null,
          left: left,
          child: Material(
              color: Colors.transparent,
              child: SizedBox(
                  width: MediaQuery.of(overlayContext).size.width,
                  child: Center(
                    child: Card(
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12.px),
                            side: const BorderSide(
                              style: BorderStyle.none,
                            )),
                        child: Padding(
                          padding: EdgeInsets.symmetric(
                              horizontal: 18.px, vertical: 15.px),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              if (count != -1)
                                Container(
                                    width: 18.px,
                                    height: 18.px,
                                    alignment: Alignment.center,
                                    margin: EdgeInsets.only(right: 8.px),
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius:
                                            BorderRadius.circular(18.px)),
                                    child: Text(
                                      '!',
                                      style: TextStyle(
                                          color: Colors.black, fontSize: 16.px),
                                    )),
                              Text(
                                count == -1
                                    ? message
                                    : message + count.toString() + 's',
                                style: textStyle,
                              ),
                            ],
                          ),
                        ),
                        color: bgColor),
                  ))));
    });

    if (!immediate) {
      Future.delayed(Duration(milliseconds: 500)).then((value) {
        // 插入到 Overlay中显示 OverlayEntry
        overlayState.insert(overlayEntry);
      });
    } else {
      overlayState.insert(overlayEntry);
    }
    if (count == -1) {
      // 延时1.5s，移除 OverlayEntry
      Future.delayed(delay).then((value) {
        if (_overlayStatus && overlayEntry.mounted) {
          overlayEntry.remove();
          _entryList.removeAt(0);
          isShow = false;
        }
      }).catchError((e) {});
      // }
    } else {
      countTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
        if (count == 0 && overlayEntry.mounted) {
          timer.cancel();
          overlayEntry.remove();
          countCallback();
          isShow = false;
        } else {
          count--;
          overlayEntry.markNeedsBuild();
        }
      });
    }

    _entryList.add(overlayEntry);
    isShow = true;
  }

  static void cancel() {
    _overlayStatus = false;
    if (_entryList.length == 0) return;
    _entryList.forEach((it) {
      if (it.mounted) it.remove();
    });
    _entryList = [];
    isShow = false;
  }
}
